package org.example.project_12.service.impl;

import org.example.project_12.dto.SpaceDto;
import org.example.project_12.dto.SpaceMemberDto;
import org.example.project_12.entity.Space;
import org.example.project_12.entity.SpaceMember;
import org.example.project_12.entity.User;
import org.example.project_12.mapper.SpaceMapper;
import org.example.project_12.mapper.SpaceMemberMapper;
import org.example.project_12.mapper.UserMapper;
import org.example.project_12.service.SpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SpaceServiceImpl implements SpaceService {

    @Autowired
    private SpaceMapper spaceMapper;

    @Autowired
    private SpaceMemberMapper spaceMemberMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public Space createSpace(Space space, Long ownerId) {
        // 检查空间名称是否重复
        Space querySpace = new Space();
        querySpace.setName(space.getName());
        querySpace.setOwnerId(ownerId);
        if (spaceMapper.selectCount(querySpace) > 0) {
            throw new RuntimeException("空间名称已存在");
        }

        // 设置空间所有者
        space.setOwnerId(ownerId);
        space.setCreatedAt(java.time.LocalDateTime.now());

        // 保存空间
        spaceMapper.insert(space);

        // 将创建者添加为空间成员（管理员权限）
        SpaceMember member = SpaceMember.builder()
                .spaceId(space.getId())
                .userId(ownerId)
                .permission("EDIT")
                .build();
        member.setAddedAt(java.time.LocalDateTime.now());
        spaceMemberMapper.insert(member);

        return space;
    }

    @Override
    @Transactional
    public boolean updateSpace(Space space, Long userId) {
        // 检查权限
        if (!isSpaceOwner(space.getId(), userId)) {
            throw new RuntimeException("无权限修改空间");
        }

        // 检查空间名称是否重复（排除当前空间）
        Space existingSpace = spaceMapper.selectById(space.getId());
        if (existingSpace != null && !existingSpace.getName().equals(space.getName())) {
            Space querySpace = new Space();
            querySpace.setName(space.getName());
            querySpace.setOwnerId(userId);
            if (spaceMapper.selectCount(querySpace) > 0) {
                throw new RuntimeException("空间名称已存在");
            }
        }

        // 更新空间信息
        return spaceMapper.update(space) > 0;
    }

    @Override
    @Transactional
    public boolean deleteSpace(Long spaceId, Long userId) {
        // 检查权限
        if (!isSpaceOwner(spaceId, userId)) {
            throw new RuntimeException("无权限删除空间");
        }

        // 删除空间成员
        SpaceMember memberQuery = new SpaceMember();
        memberQuery.setSpaceId(spaceId);
        List<SpaceMember> members = spaceMemberMapper.selectList(memberQuery);
        for (SpaceMember member : members) {
            spaceMemberMapper.deleteById(member.getId());
        }

        // 删除空间
        return spaceMapper.deleteById(spaceId) > 0;
    }

    @Override
    public SpaceDto getSpaceById(Long spaceId, Long userId) {
        Space space = spaceMapper.selectById(spaceId);
        if (space == null) {
            throw new RuntimeException("空间不存在");
        }

        // 权限检查：私有空间需要用户登录且有权限
        if ("private".equals(space.getVisibility())) {
            if (userId == null) {
                throw new RuntimeException("私有空间需要登录后才能访问");
            }
            // 检查用户是否有权限访问私有空间
            if (!isUserMemberOfSpace(spaceId, userId)) {
                throw new RuntimeException("无权限访问该空间");
            }
        }

        // 转换为DTO
        SpaceDto spaceDto = new SpaceDto();
        spaceDto.setId(space.getId());
        spaceDto.setName(space.getName());
        spaceDto.setDescription(space.getDescription());
        spaceDto.setVisibility(space.getVisibility());
        spaceDto.setOwnerId(space.getOwnerId());
        spaceDto.setCreatedAt(space.getCreatedAt());

        // 获取所有者用户名
        User owner = userMapper.selectById(space.getOwnerId());
        if (owner != null) {
            spaceDto.setOwnerName(owner.getUsername());
        }

        // 获取成员数量和文档数量
        SpaceMember memberQuery = new SpaceMember();
        memberQuery.setSpaceId(spaceId);
        spaceDto.setMemberCount(spaceMemberMapper.selectCount(memberQuery));

        // TODO: 获取文档数量（需要DocumentMapper）
        spaceDto.setDocumentCount(0);

        return spaceDto;
    }

    @Override
    public List<SpaceDto> getSpacesByOwnerId(Long userId) {
        List<Space> spaces = spaceMapper.selectByOwnerId(userId);
        
        List<SpaceDto> spaceDtos = new ArrayList<>();
        for (Space space : spaces) {
            SpaceDto dto = new SpaceDto();
            dto.setId(space.getId());
            dto.setName(space.getName());
            dto.setDescription(space.getDescription());
            dto.setVisibility(space.getVisibility());
            dto.setOwnerId(space.getOwnerId());
            dto.setCreatedAt(space.getCreatedAt());
            
            // 获取所有者用户名
            User owner = userMapper.selectById(space.getOwnerId());
            if (owner != null) {
                dto.setOwnerName(owner.getUsername());
            }
            
            // 获取成员数量
            SpaceMember memberQuery = new SpaceMember();
            memberQuery.setSpaceId(space.getId());
            dto.setMemberCount(spaceMemberMapper.selectCount(memberQuery));
            dto.setDocumentCount(0);
            
            spaceDtos.add(dto);
        }
        
        return spaceDtos;
    }

    @Override
    public List<SpaceDto> getSpacesByMemberId(Long userId) {
        List<SpaceMember> members = spaceMemberMapper.selectByUserId(userId);
        
        List<SpaceDto> spaceDtos = new ArrayList<>();
        for (SpaceMember member : members) {
            Space space = spaceMapper.selectById(member.getSpaceId());
            if (space != null && !space.getOwnerId().equals(userId)) {
                SpaceDto dto = new SpaceDto();
                dto.setId(space.getId());
                dto.setName(space.getName());
                dto.setDescription(space.getDescription());
                dto.setVisibility(space.getVisibility());
                dto.setOwnerId(space.getOwnerId());
                dto.setCreatedAt(space.getCreatedAt());
                
                // 获取所有者用户名
                User owner = userMapper.selectById(space.getOwnerId());
                if (owner != null) {
                    dto.setOwnerName(owner.getUsername());
                }
                
                // 获取成员数量
                SpaceMember memberQuery = new SpaceMember();
                memberQuery.setSpaceId(space.getId());
                dto.setMemberCount(spaceMemberMapper.selectCount(memberQuery));
                dto.setDocumentCount(0);
                
                spaceDtos.add(dto);
            }
        }
        
        return spaceDtos;
    }

    @Override
    public List<SpaceDto> getPublicSpaces() {
        List<Space> spaces = spaceMapper.selectPublicSpaces();
        
        List<SpaceDto> spaceDtos = new ArrayList<>();
        for (Space space : spaces) {
            SpaceDto dto = new SpaceDto();
            dto.setId(space.getId());
            dto.setName(space.getName());
            dto.setDescription(space.getDescription());
            dto.setVisibility(space.getVisibility());
            dto.setOwnerId(space.getOwnerId());
            dto.setCreatedAt(space.getCreatedAt());
            
            // 获取所有者用户名
            User owner = userMapper.selectById(space.getOwnerId());
            if (owner != null) {
                dto.setOwnerName(owner.getUsername());
            }
            
            // 获取成员数量
            SpaceMember memberQuery = new SpaceMember();
            memberQuery.setSpaceId(space.getId());
            dto.setMemberCount(spaceMemberMapper.selectCount(memberQuery));
            dto.setDocumentCount(0);
            
            spaceDtos.add(dto);
        }
        
        return spaceDtos;
    }

    @Override
    public List<SpaceDto> searchSpacesByName(String name, Long userId) {
        List<Space> spaces = spaceMapper.selectByNameLike(name);
        List<SpaceDto> result = new ArrayList<>();
        for (Space space : spaces) {
            // 权限过滤：私有空间只显示用户有权限的
            if ("private".equals(space.getVisibility()) && (userId == null || !isUserMemberOfSpace(space.getId(), userId))) {
                continue;
            }
            SpaceDto dto = new SpaceDto();
            dto.setId(space.getId());
            dto.setName(space.getName());
            dto.setDescription(space.getDescription());
            dto.setVisibility(space.getVisibility());
            dto.setOwnerId(space.getOwnerId());
            dto.setCreatedAt(space.getCreatedAt());
            // 获取所有者用户名
            User owner = userMapper.selectById(space.getOwnerId());
            if (owner != null) {
                dto.setOwnerName(owner.getUsername());
            }
            result.add(dto);
        }
        return result;
    }

    @Override
    @Transactional
    public boolean inviteMember(Long spaceId, Long userId, String permission, Long inviterId) {
        // 检查邀请者权限
        if (!hasPermission(spaceId, inviterId, "EDIT")) {
            throw new RuntimeException("无权限邀请成员");
        }

        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查用户是否已经是成员
        SpaceMember existingMember = spaceMemberMapper.selectBySpaceIdAndUserId(spaceId, userId);
        if (existingMember != null) {
            throw new RuntimeException("用户已经是空间成员");
        }

        // 添加成员
        SpaceMember member = SpaceMember.builder()
                .spaceId(spaceId)
                .userId(userId)
                .permission(permission)
                .build();
        member.setAddedAt(java.time.LocalDateTime.now());

        return spaceMemberMapper.insert(member) > 0;
    }

    @Override
    @Transactional
    public boolean removeMember(Long spaceId, Long memberId, Long operatorId) {
        // 检查操作者权限
        if (!isSpaceOwner(spaceId, operatorId)) {
            throw new RuntimeException("无权限移除成员");
        }

        // 不能移除自己
        if (memberId.equals(operatorId)) {
            throw new RuntimeException("不能移除自己");
        }

        // 移除成员
        SpaceMember memberQuery = new SpaceMember();
        memberQuery.setSpaceId(spaceId);
        memberQuery.setUserId(memberId);
        return spaceMemberMapper.delete(memberQuery) > 0;
    }

    @Override
    @Transactional
    public boolean updateMemberPermission(Long spaceId, Long memberId, String permission, Long operatorId) {
        // 检查操作者权限
        if (!isSpaceOwner(spaceId, operatorId)) {
            throw new RuntimeException("无权限修改成员权限");
        }

        // 查找成员
        SpaceMember member = spaceMemberMapper.selectBySpaceIdAndUserId(spaceId, memberId);
        if (member == null) {
            throw new RuntimeException("成员不存在");
        }

        // 更新权限
        member.setPermission(permission);
        return spaceMemberMapper.update(member) > 0;
    }

    @Override
    public List<SpaceMemberDto> getSpaceMembers(Long spaceId, Long userId) {
        // 获取空间信息
        Space space = spaceMapper.selectById(spaceId);
        if (space == null) {
            throw new RuntimeException("空间不存在");
        }

        // 权限检查：私有空间需要用户登录且有权限
        if ("private".equals(space.getVisibility())) {
            if (userId == null) {
                throw new RuntimeException("私有空间需要登录后才能查看成员");
            }
            if (!hasPermission(spaceId, userId, "VIEW")) {
                throw new RuntimeException("无权限查看空间成员");
            }
        }

        List<SpaceMember> members = spaceMemberMapper.selectBySpaceId(spaceId);
        
        List<SpaceMemberDto> memberDtos = new ArrayList<>();
        for (SpaceMember member : members) {
            SpaceMemberDto dto = new SpaceMemberDto();
            dto.setId(member.getId());
            dto.setSpaceId(member.getSpaceId());
            dto.setUserId(member.getUserId());
            dto.setPermission(member.getPermission());
            dto.setAddedAt(member.getAddedAt());
            
            // 获取用户信息
            User user = userMapper.selectById(member.getUserId());
            if (user != null) {
                dto.setUsername(user.getUsername());
                dto.setEmail(user.getEmail());
            }
            
            memberDtos.add(dto);
        }
        
        return memberDtos;
    }

    @Override
    public boolean hasPermission(Long spaceId, Long userId, String requiredPermission) {
        // 检查是否为空间所有者
        if (isSpaceOwner(spaceId, userId)) {
            return true;
        }

        // 检查成员权限
        SpaceMember member = spaceMemberMapper.selectBySpaceIdAndUserId(spaceId, userId);
        
        if (member == null) {
            return false;
        }

        // 权限检查逻辑
        if ("EDIT".equals(requiredPermission)) {
            return "EDIT".equals(member.getPermission());
        } else if ("VIEW".equals(requiredPermission)) {
            return "EDIT".equals(member.getPermission()) || "VIEW".equals(member.getPermission());
        }

        return false;
    }

    @Override
    public boolean isSpaceOwner(Long spaceId, Long userId) {
        Space space = spaceMapper.selectById(spaceId);
        return space != null && space.getOwnerId().equals(userId);
    }

    @Override
    public boolean isUserMemberOfSpace(Long spaceId, Long userId) {
        // 检查是否为空间所有者
        if (isSpaceOwner(spaceId, userId)) {
            return true;
        }
        
        // 检查是否为空间成员
        SpaceMember member = spaceMemberMapper.selectBySpaceIdAndUserId(spaceId, userId);
        return member != null;
    }
} 